﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using FW;
using dbiparser;
using System.Threading;
using System.Threading.Tasks;
using System.Drawing;
//using ExcelLibrary.SpreadSheet;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.HSSF.Util;
using NPOI.POIFS.FileSystem;
using NPOI.HPSF;

namespace kserv
{
    public class mpConsulta
    {

        kservDataContext db;

        private string crchave = "q1w2e3r4t5y6u7i8o9p0zaxscdvfbgnhmjkl";

        private fwlog log;
        private configSRV csrv;
        private string _msg;
        private string erro = "";
        private string uf = "";
        private List<int> servicosOS = new List<int>();
        private int _idemp;
        private long _idos;
        private long _idmp;
        private int _mpn;
        private string codigoint = "";
        private string empresaint = "";
        private string filialint = "";
        private string cidade = "";
        private int _idthread;
        private string acaoThread = "";
        private int waitThread = 0;
        public int IDTHREAD { get { return _idthread; } set { _idthread = value; } }
        private long _idexecucao;
        public long IDEXEC { get { return _idexecucao; } set { _idexecucao = value; } }
        public string ACAOTHREAD { get { return acaoThread; } }
        private Thread[] slots;

         public mpConsulta(long IDOS, int IDEMP, int IDTH, long IDEX, int MPN, long IDMP)
         {
            csrv = new configSRV();
            log = new fwlog(csrv.TEMPDIR + "\\log.dbiKcad.txt", csrv.TIPOLOG);
            _msg = "";
            db = new kservDataContext(csrv.DBINFECONNSTRING);

            _idemp = IDEMP;
            _idos = IDOS;
            _idthread = IDTH;
            _idexecucao = IDEX;
            _mpn = MPN;
            _idmp = IDMP;

            // define os serviçcos que serão executados na OS
            var serv = (from tb in db.tb_osXservs where tb.FK_IDos == _idos select new { tb.FK_IDserv });
            servicosOS = new List<int>();
            foreach (var sk in serv)
            {
                servicosOS.Add((int)sk.FK_IDserv);
            }
         }

         public class binomino
         {
             public string EMPRESA { get; set; }
             public string FILIAL { get; set; }
             public string CNPJ { get; set; }
         }

         public void arrumaArquivo()
         {



             string arqcons = csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/consultas.txt";
             string arqtemp = csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/tempconsultas.txt";
             linhaComplex lc = new linhaComplex();

             Encoding enc = Encoding.GetEncoding("ISO-8859-1");
             StreamReader sr = new StreamReader(arqcons, enc);

             int count = 0;
             string linha = "";

             // carrega cnpjs consulta.txt na lista
             List<binomino> liBi = new List<binomino>();
             //List<string> cnpjs = new List<string>();
             while (sr.Peek() >= 0)
             {

                 linha = sr.ReadLine();
                 if (count != 0)
                 {
                     lc.autoCarga(linha);
                     liBi.Add(new binomino() { EMPRESA = lc.OREMPRESA, FILIAL = lc.ORFILIAL, CNPJ = lc.ORCNPJ });
                     // cnpjs.Add(lc.ORCNPJ);
                 }

                 count++;
             }
             sr.Close();
             sr.Dispose();
             sr = null;

             sr = new StreamReader(arqtemp, enc);

             count = 0;
             linha = "";
             // compara com tempConsulta .txt e add em consulta apenas quem não esta em consulta
             while (sr.Peek() >= 0)
             {

                 linha = sr.ReadLine();
                 if (count != 0)
                 {
                     lc.autoCarga(linha);
                     if (!liBi.Any(t => t.EMPRESA == lc.OREMPRESA && t.FILIAL == lc.ORFILIAL && t.CNPJ == lc.ORCNPJ))
                     //if (  !cnpjs.Contains(lc.ORCNPJ))
                     {
                         FW.cIO.appendLine(arqcons, lc.LINHA);
                     }

                 }

                 count++;
             }
             sr.Close();
             sr.Dispose();
             sr = null;
             // adiciona cnpj de consulta.txt na lista
             string arqorig = csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/baseoriginal.txt";

             sr = new StreamReader(arqcons, enc);

             count = 0;
             linha = "";
             liBi = new List<binomino>();
             //cnpjs = new List<string>();
             while (sr.Peek() >= 0)
             {

                 linha = sr.ReadLine();
                 if (count != 0)
                 {
                     lc.autoCarga(linha);
                     liBi.Add(new binomino() { EMPRESA = lc.OREMPRESA, FILIAL = lc.ORFILIAL, CNPJ = lc.ORCNPJ });
                     //cnpjs.Add(lc.ORCNPJ);
                 }

                 count++;
             }
             sr.Close();
             sr.Dispose();
             sr = null;
             // compara com baseoriginal .txt e add em consulta apenas quem não esta em consulta
             sr = new StreamReader(arqorig, enc);

             count = 0;
             linha = "";

             while (sr.Peek() >= 0)
             {

                 linha = sr.ReadLine();
                 if (count != 0)
                 {
                     lc.autoCarga(linha);
                     if (!liBi.Any(t => t.EMPRESA == lc.OREMPRESA && t.FILIAL == lc.ORFILIAL && t.CNPJ == lc.ORCNPJ))
                     //if (!cnpjs.Contains(lc.ORCNPJ))
                     {
                         FW.cIO.appendLine(arqcons, lc.LINHA);
                         log.info("MP foi encontrado CNPJ não processado na OS", "OS="+_idos.ToString() + " MP=" + _mpn.ToString() , "Linha adicionada cnpj = " + lc.ORCNPJ.ToString());
                     }
                     else
                     {
                     }

                 }

                 count++;
             }
             sr.Close();
             sr.Dispose();
             sr = null;


             // conta registros unicos
             sr = new StreamReader(arqorig, enc);

             count = 0;
             linha = "";

             liBi = new List<binomino>();
             //cnpjs = new List<string>();
             while (sr.Peek() >= 0)
             {

                 linha = sr.ReadLine();
                 if (count != 0)
                 {

                     lc.autoCarga(linha);
                     liBi.Add(new binomino() { EMPRESA = lc.OREMPRESA, FILIAL = lc.ORFILIAL, CNPJ = lc.ORCNPJ });
                     //cnpjs.Add(lc.ORCNPJ);
                 }

                 count++;
             }

             int contagemUnicos = liBi.Distinct().Count();// cnpjs.Distinct().Count();
             log.info(string.Format("foram encontrados {0} CNPJs distintos na OS", contagemUnicos.ToString()), _idos.ToString(), "");
             sr.Close();
             sr.Dispose();
             sr = null;
             liBi.Clear();
             liBi = null;
             //cnpjs.Clear();
             //cnpjs = null;
             Thread.Sleep(2000);
         }

         private void prepararArquivoPJ()
         {
             string linha = "";
             string saida = "";
             linhaComplex lc = new linhaComplex();
             int count = 0;
             Encoding enc = Encoding.GetEncoding("ISO-8859-1");
             StreamReader sr = new StreamReader(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/baseoriginal.txt", enc);
             while (sr.Peek() >= 0)
             {
                 linha = sr.ReadLine();
                 if (count != 0)
                 {
                     lc = new linhaComplex();
                     lc.iniciar();
                     lc.autoCarga(linha);
                     if (lc.RF != "ERR")
                     {
                         lc.VR = "1";
                         lc.RF = "0";
                         lc.SI = "0";
                         lc.IB = "0";
                         lc.SN = servicosOS.Any(t => t == 6) ? "0" : "NOT";
                         lc.SU = servicosOS.Any(t => t == 3) ? "0" : "NOT";
                         lc.R0 = "NOT";
                         lc.R1 = "NOT";
                         lc.R2 = "NOT";
                         lc.R3 = "NOT";
                         lc.R4 = "NOT";
                     }
                     else
                     {
                         lc.VR = "1";
                         lc.RF = "ERR";
                         lc.SI = "ERR";
                         lc.IB = "ERR";
                         lc.SN = "ERR";
                         lc.SU = "ERR";
                         lc.R0 = "NOT";
                         lc.R1 = "NOT";
                         lc.R2 = "NOT";
                         lc.R3 = "NOT";
                         lc.R4 = "NOT";
                     }
                     saida = saida + lc.LINHA + "\r\n";
                 }
                 else
                 {
                     saida = saida + lc.CABECALHO + "\r\n";
                 }
                 count++;
             }
             sr.Close();
             sr.Dispose();
             sr = null;
             lc = null;

             cIO cio = new cIO();
             // cio.CriaDir(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/comprovantes");
             cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/baseoriginal.txt");
             cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/consultas.txt");
             cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/tempconsultas.txt");
             cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/consultasemlinha.txt");
             cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/resultado.xls");
             cio.NomeArquivo = csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/baseoriginal.txt";
             cio.Conteudo = saida;
             cio.GravarArquivo();

             cio.NomeArquivo = csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/tempconsultas.txt";
             cio.GravarArquivo();
             cio = null;
         }

         public void consultaPJ()
         {
             prepararArquivoPJ();

             // stts = 4 em processamento
             tb_osmp o = db.tb_osmps.Single(t => t.PK_IDmp == _idmp);
             o.stts = 4;
             db.SubmitChanges();
             o = null;


             disparaConsultasPJ();



         }

         public void reConsultaPJ()
         {
             // stts = 4 em processamento
             tb_osmp o = db.tb_osmps.Single(t => t.PK_IDmp == _idmp);
             //o.status = "Executando Reconsulta";
             o.stts = 4;
             db.SubmitChanges();
             o = null;

             if (reorganizaArquivoReconsulta())
             {
                 disparaConsultasPJ();
             }
             else
             {
                 o = db.tb_osmps.Single(t => t.PK_IDmp == _idmp);
                 o.dt_proxExec = DateTime.Now.AddMinutes(5d);
                 o.stts = 5;
                 db.SubmitChanges();
                 o = null;
             }


         }


         private bool reorganizaArquivoReconsulta()
         {
             bool continuar = false;
             string linha = "";
             int count = 0;
             try
             {
                 cIO cio = new cIO();
                 string temparquivo = csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/tempconsultas.txt";
                 cio.apagaArq(temparquivo);
                 cio = null;
                 linhaComplex lc = new linhaComplex();
                 Encoding enc = Encoding.GetEncoding("ISO-8859-1");
                 StreamReader sr = new StreamReader(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/consultas.txt", enc);

                 log.debug(string.Format("MP reorganiza Arquivo Consulta IDOS={0} MPM={1}  ", _idos.ToString(), _mpn.ToString()));

                 while (sr.Peek() >= 0)
                 {
                     linha = sr.ReadLine();
                     if (count != 0)
                     {
                         lc = new linhaComplex();
                         lc.autoCarga(linha);
                         //lc.VR = "1";
                         //lc.RF = "0";
                         //lc.SI = "0";
                         //lc.IB = "0";
                         if (lc.SN == "NOT")
                         {
                             lc.SN = servicosOS.Any(t => t == 6) ? "0" : "NOT";
                         }
                         if (lc.SU == "NOT")
                         {
                             lc.SU = servicosOS.Any(t => t == 3) ? "0" : "NOT";
                         }
                         //lc.R0 = "NOT";
                         //lc.R1 = "NOT";
                         //lc.R2 = "NOT";
                         //lc.R3 = "NOT";
                         //lc.R4 = "NOT";
                         FW.cIO.appendLine(temparquivo, lc.LINHA);
                     }
                     else
                     {
                         FW.cIO.appendLine(temparquivo, lc.CABECALHO);
                     }
                     count++;
                 }

                 //cio.copyFile(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/consultas.txt", csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/tempconsultas.txt");
                 sr.Close();
                 sr.Dispose();
                 sr = null;
                 cio = new cIO();
                 cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/consultas.txt");
                 cio = null;
                 continuar = true;
             }
             catch (Exception ex)
             {
                 log.erro("MP reorganizaArquivoReconsulta acesso aos arquivos", _idos.ToString() + " MP=" + _mpn.ToString(), ex.Message + "|" + ex.StackTrace);
             }

             return continuar;
         }

         private void disparaConsultasPJ()
         {

             try
             {
                 slots = new Thread[csrv.QTDTHREADSPOROS];
                 for (int i = 0; i < slots.Count(); i++)
                 {
                     slots[i] = new Thread(delegate() { Thread.Sleep(1); });
                 }
                 string rodar = "";
                 int qtd = 0;
                 string linha = "";
                 int count = 0;
                 string arquivo = csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/consultas.txt";
                 linhaComplex lc = new linhaComplex();

                 Encoding enc = Encoding.GetEncoding("ISO-8859-1");
                 StreamReader sr = new StreamReader(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/tempconsultas.txt", enc);

                 log.debug(string.Format("MP abrindo consultas IDOS {0} / MP {2} com {1} threads", _idos.ToString(), csrv.QTDTHREADSPOROS.ToString(), _mpn));

                 while (sr.Peek() >= 0)
                 {

                     linha = sr.ReadLine();
                     if (count != 0)
                     {
                         lc = new linhaComplex();
                         lc.autoCarga(linha);
                         if (acaoThread == "RUN")
                         {
                             try
                             {
                                 if (lc.RF != "OK" && lc.RF != "ERR" && lc.RF != "CNL" && lc.RF != "NOT")
                                 {
                                     // receita federal
                                     if (int.TryParse(lc.RF, out qtd))
                                     {
                                         rodar = "RF";
                                     }
                                     else
                                     {
                                         rodar = "RFERRQTD";
                                     }
                                 }
                                 else
                                 {
                                     if (lc.RF == "OK")
                                     {
                                         if (lc.SI != "OK" && lc.SI != "ERR" && lc.SI != "CNL" && lc.SI != "NOT")
                                         {
                                             //sintegra
                                             if (int.TryParse(lc.SI, out qtd))
                                             {
                                                 rodar = "SI";
                                             }
                                             else
                                             {
                                                 rodar = "SIERRQTD";
                                             }
                                         }
                                         else
                                         {
                                             if (lc.IB != "OK" && lc.IB != "ERR" && lc.IB != "CNL" && lc.IB != "NOT")
                                             {
                                                 //ibge
                                                 if (int.TryParse(lc.IB, out qtd))
                                                 {
                                                     rodar = "IB";
                                                 }
                                                 else
                                                 {
                                                     rodar = "IBERRQTD";
                                                 }
                                             }
                                             else
                                             {
                                                 if (lc.SN != "OK" && lc.SN != "ERR" && lc.SN != "CNL" && lc.SN != "NOT")
                                                 {
                                                     //Simples Nacional
                                                     if (int.TryParse(lc.SN, out qtd))
                                                     {
                                                         rodar = "SN";
                                                     }
                                                     else
                                                     {
                                                         rodar = "SNERRQTD";
                                                     }
                                                 }
                                                 else
                                                 {
                                                     if (lc.SU != "OK" && lc.SU != "ERR" && lc.SU != "CNL" && lc.SU != "NOT")
                                                     {
                                                         //SUFRAMA
                                                         // somente CNPJ do AM
                                                         if (lc.RFESTADO == "AM")
                                                         {
                                                             if (int.TryParse(lc.SU, out qtd))
                                                             {
                                                                 rodar = "SU";
                                                             }
                                                             else
                                                             {
                                                                 rodar = "SUERRQTD";
                                                             }
                                                         }
                                                         else
                                                         {
                                                             rodar = "SUNAOAM";
                                                         }
                                                     }
                                                     else
                                                     {
                                                         rodar = "REPETE";
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                     else
                                     {
                                         rodar = "RFERR";
                                     }
                                 }

                                 // executa consultas


                                 switch (rodar)
                                 {
                                     case "REPETE":
                                         FW.cIO.appendLine(arquivo, lc.LINHA);
                                         break;
                                     case "RFERR":
                                         lc.SI = "CNL";
                                         lc.IB = "CNL";
                                         lc.SN = "CNL";
                                         lc.SU = "CNL";
                                         lc.R0 = "CNL";
                                         lc.R1 = "CNL";
                                         lc.R2 = "CNL";
                                         lc.R3 = "CNL";
                                         lc.R4 = "CNL";
                                         FW.cIO.appendLine(arquivo, lc.LINHA);
                                         break;
                                     case "RF":
                                         while (true)
                                         {
                                             if (slots.Any(t => t.IsAlive == false))
                                             {
                                                 for (int it = 0; it < slots.Count(); it++)
                                                 {
                                                     if (slots[it].IsAlive == false)
                                                     {

                                                         slots[it] = new Thread(delegate() { consultasThreadMP.consultaCNPJRFV1(lc, _idos, _idemp, _mpn); });
                                                         slots[it].Start();

                                                         break;
                                                     }
                                                 }
                                                 break;
                                             }
                                             else
                                             {
                                                 Thread.Sleep(1000);
                                             }
                                         }
                                         break;
                                     case "RFERRQTD":
                                         lc.RF = "ERR";
                                         lc.RFERRCOD = "QTD not int";
                                         lc.RFERRDESCRI = "QTD definida no campo RF não é inteiro";
                                         FW.cIO.appendLine(arquivo, lc.LINHA);
                                         break;
                                     case "SI":
                                         while (true)
                                         {
                                             if (slots.Any(t => t.IsAlive == false))
                                             {
                                                 for (int it = 0; it < slots.Count(); it++)
                                                 {
                                                     if (slots[it].IsAlive == false)
                                                     {
                                                         //sintegra
                                                         slots[it] = new Thread(delegate() { consultasThreadMP.consultaCNPJSIV1(lc, _idos, _idemp, _mpn); });
                                                         slots[it].Start();

                                                         break;
                                                     }
                                                 }
                                                 break;
                                             }
                                             else
                                             {
                                                 Thread.Sleep(1000);
                                             }
                                         }
                                         break;
                                     case "SIERRQTD":
                                         lc.SI = "ERR";
                                         lc.SIERRCOD = "QTD not int";
                                         lc.SIERRDESCRI = "QTD definida no campo RF não é inteiro";
                                         FW.cIO.appendLine(arquivo, lc.LINHA);

                                         break;
                                     case "IB":
                                         while (true)
                                         {
                                             if (slots.Any(t => t.IsAlive == false))
                                             {
                                                 for (int it = 0; it < slots.Count(); it++)
                                                 {
                                                     if (slots[it].IsAlive == false)
                                                     {
                                                         // ibge
                                                         slots[it] = new Thread(delegate() { consultasThreadMP.consultaCNPJIBGEV1(lc, _idos, _idemp, _mpn); });
                                                         slots[it].Start();

                                                         break;
                                                     }
                                                 }
                                                 break;
                                             }
                                             else
                                             {
                                                 Thread.Sleep(1000);
                                             }
                                         }
                                         break;
                                     case "IBERRQTD":
                                         lc.SI = "ERR";
                                         //lc.RFERRCOD = "QTD not int";
                                         //lc.RFERRDESCRI = "QTD definida no campo RF não é inteiro";
                                         FW.cIO.appendLine(arquivo, lc.LINHA);

                                         break;
                                     case "SN":
                                         while (true)
                                         {
                                             if (slots.Any(t => t.IsAlive == false))
                                             {
                                                 for (int it = 0; it < slots.Count(); it++)
                                                 {
                                                     if (slots[it].IsAlive == false)
                                                     {
                                                         // simples
                                                         slots[it] = new Thread(delegate() { consultasThreadMP.consultaCNPJSNV1(lc, _idos, _idemp, _mpn); });
                                                         slots[it].Start();

                                                         break;
                                                     }
                                                 }
                                                 break;
                                             }
                                             else
                                             {
                                                 Thread.Sleep(1000);
                                             }
                                         }
                                         break;
                                     case "SNERRQTD":
                                         lc.SN = "ERR";
                                         lc.SNERRCOD = "QTD not int";
                                         lc.SNERRDESCRI = "QTD definida no campo RF não é inteiro";
                                         FW.cIO.appendLine(arquivo, lc.LINHA);

                                         break;
                                     case "SU":
                                         while (true)
                                         {
                                             if (slots.Any(t => t.IsAlive == false))
                                             {
                                                 for (int it = 0; it < slots.Count(); it++)
                                                 {
                                                     if (slots[it].IsAlive == false)
                                                     {
                                                         // suframa
                                                         slots[it] = new Thread(delegate() { consultasThreadMP.consultaCNPJSUV1(lc, _idos, _idemp, _mpn); });
                                                         slots[it].Start();


                                                         break;
                                                     }
                                                 }
                                                 break;
                                             }
                                             else
                                             {
                                                 Thread.Sleep(1000);
                                             }
                                         }
                                         break;
                                     case "SUERRQTD":
                                         lc.SU = "ERR";
                                         //lc.SNERRCOD = "QTD not int";
                                         //lc.SNERRDESCRI = "QTD definida no campo RF não é inteiro";
                                         FW.cIO.appendLine(arquivo, lc.LINHA);
                                         break;
                                     case "SUNAOAM":
                                         lc.SU = "OK";
                                         lc.SUERRCOD = "30-1";
                                         lc.SUERRDESCRI = "CNPJ não pertence ao AM";
                                         //lc.SNERRCOD = "QTD not int";
                                         //lc.SNERRDESCRI = "QTD definida no campo RF não é inteiro";
                                         FW.cIO.appendLine(arquivo, lc.LINHA);
                                         break;
                                 }

                             }
                             catch (Exception ex)
                             {
                                 lc.RF = "ERR";
                                 lc.RFERRCOD = "CONSULTAPJ-RF";
                                 lc.RFERRDESCRI = ex.Message.Replace("\"", "");
                                 FW.cIO.appendLine(arquivo, lc.LINHA);
                                 log.erro("MP disparaConsultasPJ", _idos.ToString(), ex.Message + "|" + ex.StackTrace);
                             }
                         }
                         else if (acaoThread == "CNL")
                         {
                             // Se thread OS cancelada

                             lc.RF = lc.RF != "OK" ? "CNL" : lc.RF;
                             lc.SI = lc.SI != "OK" ? "CNL" : lc.SI;
                             lc.IB = lc.IB != "OK" ? "CNL" : lc.IB;
                             lc.SN = lc.SN != "OK" ? "CNL" : lc.SN;
                             lc.SU = lc.SU != "OK" ? "CNL" : lc.SU;
                             lc.R0 = lc.R0 != "OK" ? "CNL" : lc.R0;
                             lc.R1 = lc.R1 != "OK" ? "CNL" : lc.R1;
                             lc.R2 = lc.R2 != "OK" ? "CNL" : lc.R2;
                             lc.R3 = lc.R3 != "OK" ? "CNL" : lc.R3;
                             lc.R4 = lc.R4 != "OK" ? "CNL" : lc.R4;

                             FW.cIO.appendLine(arquivo, lc.LINHA);
                         }
                         else
                         {
                             FW.cIO.appendLine(arquivo, lc.LINHA);
                         }
                     }
                     // count == 0
                     else
                     {
                         FW.cIO.appendLine(arquivo, lc.CABECALHO);
                     }
                     count++;

                     pararThread(count);
                     Thread.Sleep(waitThread);

                 }
                 sr.DiscardBufferedData();
                 sr.Dispose();
                 sr = null;

                 // cio = null;

                 // espera para todas as threads terminarem.
                 Thread.Sleep(180000);

                 procurarErrosConsulta();
             }
             catch (Exception ex)
             {
                 log.erro("MP disparaConsultasPJ geral", _idos.ToString(), ex.Message + "|" + ex.StackTrace);
             }
         }

         private void procurarErrosConsulta()
         {
             try
             {
                 int qtd = 0;
                 string linha = "";
                 int count = 0;
                 linhaComplex lc = new linhaComplex();
                 bool erros = false;
                 try
                 {
                     Encoding enc = Encoding.GetEncoding("ISO-8859-1");
                     StreamReader sr = new StreamReader(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _mpn.ToString() + "/consultas.txt", enc);
                     while (sr.Peek() >= 0)
                     {
                         linha = sr.ReadLine();


                         if (count != 0)
                         {
                             lc = new linhaComplex();
                             lc.autoCarga(linha);
                             if (lc.RF != "OK" && lc.RF != "ERR" && lc.RF != "CNL" && lc.RF != "NOT")
                             {
                                 erros = true;
                                 qtd++;
                             }
                             if (lc.SI != "OK" && lc.SI != "ERR" && lc.SI != "CNL" && lc.SI != "NOT")
                             {
                                 erros = true;
                                 qtd++;
                             }
                             if (lc.IB != "OK" && lc.IB != "ERR" && lc.IB != "CNL" && lc.IB != "NOT")
                             {
                                 erros = true;
                                 qtd++;
                             }
                             if (lc.SN != "OK" && lc.SN != "ERR" && lc.SN != "CNL" && lc.SN != "NOT")
                             {
                                 erros = true;
                                 qtd++;
                             }
                             if (lc.SU != "OK" && lc.SU != "ERR" && lc.SU != "CNL" && lc.SU != "NOT")
                             {
                                 erros = true;
                                 qtd++;
                             }
                             if (lc.R0 != "OK" && lc.R0 != "ERR" && lc.R0 != "CNL" && lc.R0 != "NOT")
                             {
                                 erros = true;
                                 qtd++;
                             }
                             if (lc.R1 != "OK" && lc.R1 != "ERR" && lc.R1 != "CNL" && lc.R1 != "NOT")
                             {
                                 erros = true;
                                 qtd++;
                             }
                             if (lc.R2 != "OK" && lc.R2 != "ERR" && lc.R2 != "CNL" && lc.R2 != "NOT")
                             {
                                 erros = true;
                                 qtd++;
                             }
                             if (lc.R3 != "OK" && lc.R3 != "ERR" && lc.R3 != "CNL" && lc.R3 != "NOT")
                             {
                                 erros = true;
                                 qtd++;
                             }
                             if (lc.R4 != "OK" && lc.R4 != "ERR" && lc.R4 != "CNL" && lc.R4 != "NOT")
                             {
                                 erros = true;
                                 qtd++;
                             }


                             //if (lc.RF != "OK" && lc.RF != "ERR" && lc.RF != "CNL" && lc.RF != "NOT" &&
                             //    lc.SI != "OK" && lc.SI != "ERR" && lc.SI != "CNL" && lc.SI != "NOT" &&
                             //    lc.IB != "OK" && lc.IB != "ERR" && lc.IB != "CNL" && lc.IB != "NOT" &&
                             //    lc.SN != "OK" && lc.SN != "ERR" && lc.SN != "CNL" && lc.SN != "NOT" &&
                             //    lc.SU != "OK" && lc.SU != "ERR" && lc.SU != "CNL" && lc.SU != "NOT" &&
                             //    lc.R0 != "OK" && lc.R0 != "ERR" && lc.R0 != "CNL" && lc.R0 != "NOT" &&
                             //    lc.R1 != "OK" && lc.R1 != "ERR" && lc.R1 != "CNL" && lc.R1 != "NOT" &&
                             //    lc.R2 != "OK" && lc.R2 != "ERR" && lc.R2 != "CNL" && lc.R2 != "NOT" &&
                             //    lc.R3 != "OK" && lc.R3 != "ERR" && lc.R3 != "CNL" && lc.R3 != "NOT" &&
                             //    lc.R4 != "OK" && lc.R4 != "ERR" && lc.R4 != "CNL" && lc.R4 != "NOT"
                             //    )

                             ////if (int.TryParse(lc.RF, out qtd) ||
                             ////    int.TryParse(lc.SI, out qtd) ||
                             ////    int.TryParse(lc.IB, out qtd) ||
                             ////    int.TryParse(lc.SN, out qtd) ||
                             ////    int.TryParse(lc.SU, out qtd) ||
                             ////    int.TryParse(lc.R0, out qtd) ||
                             ////    int.TryParse(lc.R1, out qtd) ||
                             ////    int.TryParse(lc.R2, out qtd) ||
                             ////    int.TryParse(lc.R3, out qtd) ||
                             ////    int.TryParse(lc.R4, out qtd))
                             //{
                             //    erros = true;
                             //    qtd++;
                             //}
                             //else
                             //{
                             //    erros = false;
                             //}
                             ////cio.appendLine("\"OR\";" + linha);
                             //List<string> campos = linha2List(linha);
                             //tipoLinha = campos[0].ToString();
                             //if (tipoLinha.Contains("err"))
                             //{
                             //    erros = true;         
                             //}
                         }
                         count++;
                     }
                     sr.DiscardBufferedData();
                     sr.Dispose();
                     sr = null;
                 }
                 catch (Exception ex)
                 {
                     log.erro("MP procurarErrosConsulta acesso ao arquivo", _idos.ToString(), ex.Message + "|" + ex.StackTrace);
                 }
                 tb_osmp o = db.tb_osmps.Single(t => t.PK_IDmp == _idmp);
                 //o.stts = (erros) ? 5 : 9;
                 if (acaoThread == "RUN")
                 {
                     if (qtd > 0)
                     {
                         //o.status = "Aguardando para executar reconsulta";
                         o.stts = 5;
                         o.dt_proxExec = DateTime.Now.AddMinutes(5d);
                         acaoThread = "FIM";
                     }
                     else
                     {
                         //o.status = "Aguardando fechamento de arquivos";
                         o.stts = 9;
                         acaoThread = "FIM";
                     }
                 }
                 else
                 {
                    // o.status = "Thread Cancelada";
                     o.stts = 6;
                     o.dt_proxExec = DateTime.Now;
                     acaoThread = "CNL";
                 }
                 db.SubmitChanges();
                 o = null;
             }
             catch (Exception ex)
             {
                 log.erro("MP procurarErrosConsulta", _idos.ToString(), ex.Message + "|" + ex.StackTrace);
             }
         }

         private string csv2quotecsv(string _linha)
         {
             string ret = "";
             bool achouAspas = false;
             _linha = _linha.Replace("\n", "").Replace("\r", "");
             string campo = "";
             List<string> campos = new List<string>();

             for (int i = 0; i < _linha.Length; i++)
             {
                 if ((_linha.Substring(i, 1) == ";") && !achouAspas)
                 {
                     campos.Add(campo);
                     campo = "";
                 }
                 else
                 {
                     if (_linha.Substring(i, 1) == "\"")
                     {
                         achouAspas = achouAspas ? false : true;
                     }
                     else
                     {
                         campo = campo + _linha.Substring(i, 1);
                     }
                 }
                 if ((i + 1) == _linha.Length)
                 {
                     campos.Add(campo);
                 }
             }

             foreach (string s in campos)
             {
                 ret = ret + "\"" + s + "\";";
             }


             return ret;
         }

         private List<string> linha2List(string _linha)
         {
             List<string> ls = new List<string>();
             string campo = "";
             bool a1 = false; // primeira aspas
             bool a2 = false; // segunda aspas
             for (int x = 0; x < _linha.Length - 1; x++)
             {
                 if (_linha.Substring(x, 1) == "\"")
                 {
                     if (a1 && !a2)
                     {
                         a1 = false;
                         a2 = true;
                     }
                     else if (!a1 && a2)
                     {
                         a1 = true;
                         a2 = false;
                     }
                     else
                     {
                         a1 = true;
                         a2 = false;
                     }
                 }

                 if (a1 && !a2 && _linha.Substring(x, 1) != "\"")
                 {
                     campo = campo + _linha.Substring(x, 1);
                 }

                 if (!a1 && a2 && _linha.Substring(x, 1) == "\"")
                 {
                     ls.Add(campo);
                     campo = "";
                 }

             }


             return ls;
         }

         private string cortaString(string _original, int _tamanho)
         {
             string ret = "";
             if (_original.Length > _tamanho)
             {
                 ret = _original.Substring(0, _tamanho);
             }
             else
             {
                 ret = _original;
             }
             return ret;

         }

         private string verificaFormatCNPJ(string _cnpj, out bool _continuar)
         {
             //osEstat.qtdCNPJs++;
             string saida = "\"VF\";";
             bool ret = FW.validador.ValidaCnpj(_cnpj);
             saida = saida + "\"" + codigoint + "\";";
             saida = saida + "\"" + empresaint + "\";";
             saida = saida + "\"" + filialint + "\";";
             saida = saida + "\"" + _cnpj.Replace(".", "").Replace("/", "").Replace("-", "").Replace(" ", "") + "\";";
             saida = saida + "\"" + (ret ? "TRUE" : "FALSE") + "\";";
             _continuar = ret;
             return saida;
         }

         private string verificaFormatCPF(string _cpf, out bool _continuar)
         {
             string saida = "\"VF\";";
             bool ret = FW.validador.ValidaCPF(_cpf);
             saida = saida + "\"" + codigoint + "\";";
             saida = saida + "\"" + empresaint + "\";";
             saida = saida + "\"" + filialint + "\";";
             saida = saida + "\"" + _cpf.Replace(".", "").Replace("/", "").Replace("-", "").Replace(" ", "") + "\";";
             saida = saida + "\"" + (ret ? "TRUE" : "FALSE") + "\";";
             _continuar = ret;
             return saida;
         }





         private void pararThread(long _qtd)
         {
             tb_threadsMP ttd = db.tb_threadsMPs.Single(t => t.PK_IDt == _idthread);
             db.Refresh(System.Data.Linq.RefreshMode.KeepChanges, ttd);
             acaoThread = ttd.stts;
             waitThread = (int)ttd.wait;
             ttd.qtd = _qtd;
             db.SubmitChanges();
             ttd = null;
         }

        

         public void finalizaPJ()
         {
             cIO cio = new cIO();
             string linha = "";
             int count = 0;
             string basePath = csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/{0}/consultas.txt";
             string Saida = csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/consultas.txt";
             string Saida2 = csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/baseoriginal.txt";
             cio.apagaArq(Saida);
             cio.apagaArq(Saida2);
             cio = null;
             Thread.Sleep(2000);


             linhaComplex lc = new linhaComplex();
             cIO.appendLine(Saida, lc.CABECALHO);
             cIO.appendLine(Saida2, lc.CABECALHO);

             List<tb_osmp> lmp = (from tb in db.tb_osmps
                                  where tb.FK_IDemp == _idemp && tb.FK_IDos == _idos && tb.stts == 9
                                  select tb).ToList<tb_osmp>();

             foreach (tb_osmp mp in lmp)
             {
                 Encoding enc = Encoding.GetEncoding("ISO-8859-1");
                 StreamReader sr = new StreamReader(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + mp.MPN.ToString() + "/consultas.txt", enc);
                 StreamReader sr2 = new StreamReader(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + mp.MPN.ToString() + "/baseoriginal.txt", enc);
                 count = 0;
                 while (sr.Peek() >= 0)
                 {
                     linha = sr.ReadLine();
                     if (count != 0)
                     {
                         cIO.appendLine(Saida, linha);
                     }
                     count++;
                 }

                 count = 0;
                 while (sr2.Peek() >= 0)
                 {
                     linha = sr2.ReadLine();
                     if (count != 0)
                     {
                         cIO.appendLine(Saida2, linha);
                     }
                     count++;
                 }

                 tb_osmp tmp = db.tb_osmps.Single(t => t.PK_IDmp == mp.PK_IDmp);
                 tmp.stts = 10;
                 db.SubmitChanges();
             }


             tb_o to = db.tb_os.Single(t => t.PK_IDos == _idos);
             to.stts = 9;
             to.status = "Aguardando fechamento de arquivos MultiPart";
             db.SubmitChanges();

         }




    }


    public class mptconsulta
    {
        private long _idos;
        private int _idemp;
        private int _idthread;
        private int _tpps;
        private long _idmp;
        private int _mpn;
        private Task task;
        kservDataContext db;


        private fwlog log;
        private configSRV csrv;
        //private Thread th;

        public mptconsulta(long IDOS, int IDEMP, int IDTHREAD, int TPPS, long IDMP, int MPn)
        {
            _idos = IDOS;
            _idemp = IDEMP;
            _idthread = IDTHREAD;
            _tpps = TPPS;
            _idmp = IDMP;
            _mpn = MPn;
            csrv = new configSRV();
            log = new fwlog(csrv.TEMPDIR + "\\log.dbiKcad.txt", csrv.TIPOLOG);
            db = new kservDataContext(csrv.DBINFECONNSTRING);
        }

        public void comecar()
        {
            tb_os_execucoe tex = new tb_os_execucoe()
            {
                dt_inicio = DateTime.Now,
                FK_IDos = _idos,
                FK_IDthread = _idthread,
                stts = "RUN"
            };

            db.tb_os_execucoes.InsertOnSubmit(tex);
            db.SubmitChanges();
            long idexec = tex.PK_IDexec;

            tb_threadsMP tth = db.tb_threadsMPs.Single(t => t.PK_IDt == _idthread);
            tth.FK_IDos = _idos;
            tth.FK_IDMP = _idmp;
            tth.dt_inicio = tex.dt_inicio;
            tth.wait = 2000;
            tth.qtd = 0;
            tth.stts = "RUN";
            db.SubmitChanges();


            mpConsulta cons = new mpConsulta(_idos, _idemp, _idthread, idexec, _mpn, _idmp);
            Action act;
            //if (_tpps == 3)
            //{
                act = new Action(cons.consultaPJ);
            //}
            //else
            //{
            //    act = new Action(cons.consultaPF);
            //}

            IAsyncResult result = act.BeginInvoke(OnActionCompleted, act);

            cons = null;
        }


        public void reComecar()
        {
            tb_os_execucoe tex = new tb_os_execucoe()
            {
                dt_inicio = DateTime.Now,
                FK_IDos = _idos,
                FK_IDthread = _idthread,
                stts = "RUN"
            };

            db.tb_os_execucoes.InsertOnSubmit(tex);
            db.SubmitChanges();
            long idexec = tex.PK_IDexec;

            tb_threadsMP tth = db.tb_threadsMPs.Single(t => t.PK_IDt == _idthread);
            tth.FK_IDos = _idos;
            tth.FK_IDMP = _idmp;
            tth.dt_inicio = tex.dt_inicio;
            tth.wait = 2000;
            tth.qtd = 0;
            tth.stts = "RUN";
            db.SubmitChanges();


            mpConsulta cons = new mpConsulta(_idos, _idemp, _idthread, idexec, _mpn, _idmp);
            Action act;
            //if (_tpps == 3)
            //{
                act = new Action(cons.reConsultaPJ);
            //}
            //else
            //{
            //    act = new Action(cons.reConsultaPF);
            //}
            IAsyncResult result = act.BeginInvoke(OnActionCompleted, act);

            cons = null;
        }

        public void finalizarArquivos()
        {

            tb_os_execucoe tex = new tb_os_execucoe()
            {
                dt_inicio = DateTime.Now,
                FK_IDos = _idos,
                FK_IDthread = _idthread,
                stts = "RUN"
            };

            db.tb_os_execucoes.InsertOnSubmit(tex);
            db.SubmitChanges();
            long idexec = tex.PK_IDexec;

            tb_threadsMP tth = db.tb_threadsMPs.Single(t => t.PK_IDt == _idthread);
            tth.FK_IDos = _idos;
            tth.FK_IDMP = _idmp;
            tth.dt_inicio = tex.dt_inicio;
            tth.wait = 2000;
            tth.qtd = 0;
            tth.stts = "RUN";
            db.SubmitChanges();


            mpConsulta cons = new mpConsulta(_idos, _idemp, _idthread, idexec, _mpn, _idmp);
            Action act;
            //if (_tpps == 3)
            //{
                act = new Action(cons.finalizaPJ);
            //}
            //else
            //{
            //    act = new Action(cons.finalizaPF);
            //}
            IAsyncResult result = act.BeginInvoke(OnActionCompleted, act);

            cons = null;

        }

        private static void OnActionCompleted(IAsyncResult result)
        {
            kservDataContext db;
            fwlog log;
            configSRV csrv;
            csrv = new configSRV();
            log = new fwlog(csrv.TEMPDIR + "\\log.dbiKcad.txt", csrv.TIPOLOG);
            db = new kservDataContext(csrv.DBINFECONNSTRING);

            var action = (Action)result.AsyncState;
            action.EndInvoke(result);

            tb_os_execucoe tex = db.tb_os_execucoes.Single(t => t.PK_IDexec == ((mpConsulta)action.Target).IDEXEC);
            tex.dt_fim = DateTime.Now;
            tex.stts = ((mpConsulta)action.Target).ACAOTHREAD;
            db.SubmitChanges();

            tb_threadsMP tth = db.tb_threadsMPs.Single(t => t.PK_IDt == ((mpConsulta)action.Target).IDTHREAD);
            tth.FK_IDos = 0;
            tth.FK_IDMP = 0;
            tth.qtd = 0;
            tth.wait = 0;
            tth.dt_inicio = new DateTime(1901, 1, 1);
            tth.stts = "OPN";

            db.SubmitChanges();
        }


    }


    public class mpcontrole
    {
        kservDataContext db;
        private fwlog log;
        private configSRV csrv;
        //private Thread th;
        private mptconsulta[] tcons;

        public mpcontrole()
        {
            csrv = new configSRV();
            log = new fwlog(csrv.TEMPDIR + "\\log.dbiKcad.txt", csrv.TIPOLOG);
            db = new kservDataContext(csrv.DBINFECONNSTRING);
        }

        private string csv2quotecsv(string _linha)
        {
            string ret = "";
            bool achouAspas = false;
            _linha = _linha.Replace("\n", "").Replace("\r", "");
            string campo = "";
            List<string> campos = new List<string>();

            for (int i = 0; i < _linha.Length; i++)
            {
                if ((_linha.Substring(i, 1) == ";") && !achouAspas)
                {
                    campos.Add(campo);
                    campo = "";
                }
                else
                {
                    if (_linha.Substring(i, 1) == "\"")
                    {
                        achouAspas = achouAspas ? false : true;
                    }
                    else
                    {
                        campo = campo + _linha.Substring(i, 1);
                    }
                }
                if ((i + 1) == _linha.Length)
                {
                    campos.Add(campo);
                }
            }

            foreach (string s in campos)
            {
                ret = ret + "\"" + s + "\";";
            }


            return ret;
        }

        public void rearranjaArquivos()
        {
            try
            {
                mpConsulta cons;
                log.info("Inicio Rearranjo MP", "", "");
                var lth = (from tb in db.tb_threadsMPs
                           from to in db.tb_osmps
                           where (tb.tipo == "CON" || tb.tipo == "RCN") && tb.stts == "RUN"
                           && tb.FK_IDMP == to.PK_IDmp
                           && to.tpps == 3
                           && to.stts == 4
                           select new
                           {
                               IDOS = (long)to.FK_IDos,
                               IDMP = (long)to.PK_IDmp,
                               MPM = (int)to.MPN,
                               IDEMP = to.FK_IDemp,
                               //TPPS = 3,
                               IDTH = tb.PK_IDt
                           }
                                       );
                foreach (var it in lth)
                {
                    log.info("MP reconstruir consultas.txt da OS", "OS=" + it.IDOS.ToString() + " MP=" + it.IDMP.ToString(), "");
                    cons = new mpConsulta((long)it.IDOS, (int)it.IDEMP, 0, 0, it.MPM, it.IDMP);
                    cons.arrumaArquivo();
                    tb_osmp tos = db.tb_osmps.Single(t => t.PK_IDmp == it.IDMP);
                    tos.stts = 5;
                    db.SubmitChanges();
                    tb_threadsMP tth = db.tb_threadsMPs.Single(t => t.PK_IDt == it.IDTH);
                    tth.stts = "OPN";
                    tth.FK_IDMP = 0;
                    tth.qtd = 0;
                    tth.FK_IDos = 0;
                    db.SubmitChanges();
                    log.info("MP reconstrução da OS concluida", "OS=" + it.IDOS.ToString() + " MP=" + it.IDMP.ToString(), "");

                }
            }
            catch (Exception ex)
            {
                log.erro("MPcontrole.rearranjaarquivos", "", ex.Message + "|" + ex.StackTrace);
                throw (ex);
            }
        }





        private void quebraArquivoPJ(int _idemp, int _idos )
        {
            try
            {
                // define os serviçcos que serão executados na OS
                var serv = (from tb in db.tb_osXservs where tb.FK_IDos == _idos select new { tb.FK_IDserv });
                List<int> servicosOS = new List<int>();
                foreach (var sk in serv)
                {
                    servicosOS.Add((int)sk.FK_IDserv);
                }

                linhaComplex lc = new linhaComplex();
                tb_osmp tbosmp = new tb_osmp();
                int multipartTamanho = csrv.MULTIPARTTAMANHO;
                cIO cio = new cIO();
                int _idpart = 0;
                string linha = "";
                string cabecalho = "";
                string saida = "";
                int count = 0;
                Encoding enc = Encoding.GetEncoding("ISO-8859-1");
                StreamReader sr = new StreamReader(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/original.txt", enc);
                cio.CriaDir(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/comprovantes");
                while (sr.Peek() >= 0)
                {

                    linha = sr.ReadLine();
                    if (count != 0)
                    {
                        lc = new linhaComplex();
                        lc.iniciar();
                        List<string> camps = FW.utils.linha2List(csv2quotecsv(linha));
                        lc.VR = "1";
                        lc.RF = "0";
                        lc.SI = "0";
                        lc.IB = "0";
                        lc.SN = servicosOS.Any(t => t == 6) ? "0" : "NOT";
                        lc.SU = servicosOS.Any(t => t == 3) ? "0" : "NOT";
                        lc.R0 = "NOT";
                        lc.R1 = "NOT";
                        lc.R2 = "NOT";
                        lc.R3 = "NOT";
                        lc.R4 = "NOT";
                        lc.ORCODIGO = camps[0];
                        lc.OREMPRESA = camps[1];
                        lc.ORFILIAL = camps[2];
                        lc.ORCNPJ = camps[3].Replace(".", "").Replace("/", "").Replace("-", "").Replace(" ", "").Replace("\"", "");
                        long pj = 0;
                        if (long.TryParse(lc.ORCNPJ, out pj))
                        {
                            lc.ORCNPJ = string.Format("{0:00000000000000}", Convert.ToInt64(lc.ORCNPJ));
                            if (!FW.validador.ValidaCnpj(lc.ORCNPJ))
                            {
                                lc.ORCNPJ = lc.ORCNPJ;
                                lc.RFERRCOD = "CNPJ INVALIDO";
                                lc.RFERRDESCRI = "CNPJ INVALIDO";
                                lc.RF = "ERR";
                            }
                        }
                        else
                        {
                            lc.ORCNPJ = lc.ORCNPJ;
                            lc.RFERRCOD = "CNPJ INVALIDO";
                            lc.RFERRDESCRI = "CNPJ INVALIDO";
                            lc.RF = "ERR";
                        }
                        lc.ORRAZAO = camps[4];
                        lc.ORFANTASIA = camps[5];
                        lc.ORLOGRADOURO = camps[6];
                        lc.ORNUM = camps[7];
                        lc.ORCOMPLEMENTO = camps[8];
                        lc.ORBAIRRO = camps[9];
                        lc.ORMUNICIPIO = camps[10];
                        lc.ORUF = camps[11];
                        lc.ORCEP = camps[12];
                        lc.ORIE = camps[13];
                        lc.ORIBGE = camps[14];
                        lc.ORCCM = camps[15];
                        lc.ORCNAE = camps[16];
                        lc.ORSUFRAMA = camps[17];

                        saida = saida + lc.LINHA + "\r\n";
                    }
                    else
                    {
                        cabecalho = lc.CABECALHO + "\r\n";
                        saida = cabecalho;
                    }

                    //if (count == 0)
                    //    cabecalho = csv2quotecsv(linha) + "\r\n";
                    //saida = saida + csv2quotecsv(linha) + "\r\n";
                    count++;
                    if (count % multipartTamanho == 0)
                    {
                        _idpart++;
                        cio.CriaDir(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _idpart.ToString());
                        cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _idpart.ToString() + "/baseoriginal.txt");
                        cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _idpart.ToString() + "/consultas.txt");
                        cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _idpart.ToString() + "/tempconsultas.txt");
                        cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _idpart.ToString() + "/consultasemlinha.txt");
                        cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _idpart.ToString() + "/resultado.xls");
                        cio.NomeArquivo = csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _idpart.ToString() + "/baseoriginal.txt";
                        cio.Conteudo = saida;
                        cio.GravarArquivo();
                        tbosmp = new tb_osmp() { FK_IDemp = _idemp, FK_IDos = _idos, MPN = _idpart, dt_proxExec = DateTime.Now, stts = 3, tpps = 3, qtd_registros = multipartTamanho, qtd_processada = 0 };
                        db.tb_osmps.InsertOnSubmit(tbosmp);
                        db.SubmitChanges();
                        saida = cabecalho;
                    }
                }

                _idpart++;
                cio.CriaDir(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _idpart.ToString());
                cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _idpart.ToString() + "/baseoriginal.txt");
                cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _idpart.ToString() + "/consultas.txt");
                cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _idpart.ToString() + "/tempconsultas.txt");
                cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _idpart.ToString() + "/consultasemlinha.txt");
                cio.apagaArq(csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _idpart.ToString() + "/resultado.xls");
                cio.NomeArquivo = csrv.TEMPDIR + "/" + _idemp.ToString() + "/" + _idos.ToString() + "/mp/" + _idpart.ToString() + "/baseoriginal.txt";
                cio.Conteudo = saida;
                cio.GravarArquivo();
                tbosmp = new tb_osmp() { FK_IDemp = _idemp, FK_IDos = _idos, MPN = _idpart, dt_proxExec = DateTime.Now, stts = 3, tpps = 3, qtd_registros = count % multipartTamanho, qtd_processada = 0 }; db.tb_osmps.InsertOnSubmit(tbosmp);
                db.SubmitChanges();
                cio = null;
            }
            catch (Exception ex)
            {
                log.erro("MPcontrole.quebraArquivoPJ", "", ex.Message + "|" + ex.StackTrace);
                throw (ex);
            }

        }

        public void iniciarServicosConsultas()
        {
            try
            {
                log.info("Inicio mpConsultas", "", "");
                List<tb_thread> lth = (from tb in db.tb_threads
                                       where tb.tipo == "CON" && tb.stts == "OPN"
                                       select tb).ToList<tb_thread>();

                tcons = new mptconsulta[lth.Count];

                List<tb_o> los = (from tb in db.tb_os
                                  where tb.stts == 3 && tb.dt_proxExec <= DateTime.Now && tb.multipart == true
                                  select tb).ToList<tb_o>();
                // quebra arquivos
                if (los.Count > 0)
                {
                    for (int i = 0; i < lth.Count; i++)
                    {
                        if (i <= los.Count - 1)
                        {
                            //string path = csrv.TEMPDIR + "/" + los[i].FK_IDemp.ToString() + "/" + los[i].PK_IDos.ToString();
                            quebraArquivoPJ((int)los[i].FK_IDemp, (int)los[i].PK_IDos);
                            tb_o to = db.tb_os.Single(t => t.PK_IDos == (int)los[i].PK_IDos);
                            to.stts = 4;
                            to.status = "Em Processamento MultiPart";
                            db.SubmitChanges();
                            //log.info("mpconsulta OS = ", los[i].PK_IDos.ToString(), "");
                            //tcons[i] = new mptconsulta(los[i].PK_IDos, (int)los[i].FK_IDemp, lth[i].PK_IDt, (int)los[i].tpps);
                            //tcons[i].comecar();
                        }
                    }
                }

                List<tb_threadsMP> lthmp = (from tb in db.tb_threadsMPs
                                            where tb.tipo == "CON" && tb.stts == "OPN"
                                            select tb).ToList<tb_threadsMP>();

                tcons = new mptconsulta[lthmp.Count];

                List<tb_osmp> lmp = (from tb in db.tb_osmps
                                     where tb.stts == 3 && tb.dt_proxExec <= DateTime.Now
                                     select tb).ToList<tb_osmp>();
                if (lmp.Count > 0)
                {
                    for (int i = 0; i < lthmp.Count; i++)
                    {
                        if (i <= lmp.Count - 1)
                        {

                            log.info("mpconsulta OS = ", lmp[i].FK_IDos.ToString(), "");
                            tcons[i] = new mptconsulta((long)lmp[i].FK_IDos, (int)lmp[i].FK_IDemp, (int)lthmp[i].PK_IDt, (int)lmp[i].tpps, (long)lmp[i].PK_IDmp, (int)lmp[i].MPN);
                            tcons[i].comecar();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.erro("MPcontrole.IniciarServicoConsultas", "", ex.Message + "|" + ex.StackTrace);
                throw (ex);
            }
        }


        public void iniciarServicosReConsultas()
        {
            try
            {
                log.info("Inicio mpREConsultas", "", "");
                List<tb_threadsMP> lth = (from tb in db.tb_threadsMPs
                                          where tb.tipo == "RCN" && tb.stts == "OPN"
                                          select tb).ToList<tb_threadsMP>();

                tcons = new mptconsulta[lth.Count];

                List<tb_osmp> los = (from tb in db.tb_osmps
                                     where tb.stts == 5 && tb.dt_proxExec <= DateTime.Now
                                     select tb).ToList<tb_osmp>();
                if (los.Count > 0)
                {
                    for (int i = 0; i < lth.Count; i++)
                    {
                        if (i <= los.Count - 1)
                        {
                            log.info("mpREconsulta OS = ", los[i].FK_IDos.ToString(), "");
                            tcons[i] = new mptconsulta((long)los[i].FK_IDos, (int)los[i].FK_IDemp, (int)lth[i].PK_IDt, (int)los[i].tpps, (long)los[i].PK_IDmp, (int)los[i].MPN);
                            //tcons[i] = new mptconsulta(los[i].PK_IDos, (int)los[i].FK_IDemp, lth[i].PK_IDt, (int)los[i].tpps);
                            tcons[i].reComecar();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.erro("MPcontrole.iniciarServicosReConsultas", "", ex.Message + "|" + ex.StackTrace);
                throw (ex);
            }
        }

        public void iniciarFinalizacaoArquivos()
        {
            try
            {
                log.info("Inicio mpFechamento", "", "");
                List<tb_threadsMP> lth = (from tb in db.tb_threadsMPs
                                          where tb.tipo == "ARQ" && tb.stts == "OPN"
                                          select tb).ToList<tb_threadsMP>();

                tcons = new mptconsulta[lth.Count];


                List<tb_o> lo = (from tb in db.tb_os
                                 where tb.stts == 4 && tb.multipart == true
                                 select tb).ToList<tb_o>();
                int thcount = 0;
                foreach (tb_o to in lo)
                {
                    if (!db.tb_osmps.Any(t => t.FK_IDos == to.PK_IDos && t.FK_IDemp == to.FK_IDemp && t.stts != 9))
                    {
                        string a = "qwer";
                        if (thcount < lth.Count)
                        {
                            log.info("mpFechamento OS = ", to.PK_IDos.ToString(), "");
                            tcons[thcount] = new mptconsulta((long)to.PK_IDos, (int)to.FK_IDemp, (int)lth[thcount].PK_IDt, (int)to.tpps, 0, 0);
                            tcons[thcount].finalizarArquivos();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.erro("MPcontrole.IniciarFinalizacaoArquivos", "", ex.Message + "|" + ex.StackTrace);
                throw (ex);
            }
        }
    }

}
